import pyautogui
import pyperclip

import win32gui
import win32api
import win32con
import time
import mss
import cv2
import numpy
import pathlib
import config.globalVariable as Gv
from datetime import datetime
import json
#备注等待时间
bz_wait_time = [4,3,2,1]
#之间等待时间
between_wait_time = [2,1.5,1,0.5]
interval_wait_time = [3,2,1.5,0.5]
num_wait_time = [1.5,1.2,0.7,0.5]
num_interval_wait_time = [1,0.7,0.3,0.1]

def get_clasname(hwnd):
    '''通过句柄获得【窗口类名】'''
    clasname = win32gui.GetClassName(hwnd)
    print('窗口类名:%s' % (clasname))
    return clasname

def pressdownCtrlOr(key):
    '''按下Ctrl+I'''
    # 模拟按下Ctrl键
    win32api.keybd_event(win32con.VK_CONTROL, 0, 0, 0)  # 0x11 是 Ctrl 键的十六进制虚拟键码
    # 模拟按下I键
    win32api.keybd_event(ord(key), 0, 0, 0)
    # 模拟释放I键
    win32api.keybd_event(ord(key), 0, win32con.KEYEVENTF_KEYUP, 0)
    # # 模拟按下I键
    # win32api.keybd_event(ord('A'), 0, 0, 0)
    # # 模拟释放I键
    # win32api.keybd_event(ord('A'), 0, win32con.KEYEVENTF_KEYUP, 0)
    # 模拟释放Ctrl键
    win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)

def pressdownCode(code):
    '''按下代码'''
    vk_codes = [ord(c) for c in code]
    time.sleep(0.1)
    for vk_code in vk_codes:
        win32api.keybd_event(vk_code, 0, 0, 0)  # 按下按键
        win32api.keybd_event(vk_code, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键

def pressdown(key):
    # 模拟按下回车键
    win32api.keybd_event(key, 0, 0, 0)  # 按下回车键
    win32api.keybd_event(key, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放回车键

def pressdownCodeApi(code):
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄将窗口放到最前
        win32gui.SetForegroundWindow(hwnd)
        # 要发送的字符串
        pressdownCode(code)
        pressdown(win32con.VK_RETURN)

def setBeiZhuByCode(code,text,hwnd,xoff,yoff,y2off,check):
    # 将字符串转换为虚拟键码列表
    pressdownCode(code)
    pressdown(win32con.VK_RETURN)
    time.sleep(0.1)
    pressdown(win32con.VK_INSERT)
    pressdownCtrlOr('I')
    time.sleep(2)
    pyperclip.copy(text)
    pressdownCtrlOr('A')
    pressdown(win32con.VK_DELETE)
    # 获取标准输出句柄
    # 发送消息
    time.sleep(0.1)
    pressdownCtrlOr('V')
    # 获得屏幕的分辨率
    monitor_rect = win32gui.GetWindowRect(hwnd)
    # 计算副屏中央位置的坐标
    center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2
    center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2
    if xoff is None or len(xoff)<=0 or yoff is None or len(yoff)<=0 or y2off is None or len(y2off)<=0:
        off_x = int(center_x / 66.84)
        off_y = int(center_y / 5.13)
        off_y2 = off_y+20
    else:
        off_x = int(xoff)
        off_y = int(yoff)
        off_y2 = int(y2off)
    if check:
        #移动到简字
        win32api.SetCursorPos((center_x + off_x, center_y+off_y2))
        pyautogui.click()
        pressdownCtrlOr('A')
        pressdown(win32con.VK_DELETE)
        pressdownCtrlOr('V')

    win32api.SetCursorPos((center_x + off_x, center_y + off_y))
    pyautogui.click()

def setXYOff(xoff:int,yoff:int):
    if xoff is None or yoff is None:
        return
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄将窗口放到最前
        win32gui.SetForegroundWindow(hwnd)
        # 获得屏幕的分辨率
        monitor_rect = win32gui.GetWindowRect(hwnd)
        # 计算副屏中央位置的坐标
        center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2
        center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2
        win32api.SetCursorPos((center_x + xoff, center_y + yoff))
        pyautogui.click()


def setXYNumOff():
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
        win32gui.SetForegroundWindow(hwnd)
        # 获得屏幕的分辨率
        monitor_rect = win32gui.GetWindowRect(hwnd)
        # 计算副屏中央位置的坐标
        center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2 // 4
        center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2 // 4
        print(monitor_rect)
        print(center_y)
        win32api.SetCursorPos((center_x, center_y))
        time.sleep(1)
        pyautogui.rightClick()
        num =  0.925
        i = 0.925 - 0.77
        y = 0
        win32api.SetCursorPos((center_x + int((center_x/35.91)) , center_y + int((center_y / 0.925)) ))
        time.sleep(0.5)
        win32api.SetCursorPos((center_x + int((center_x/7.182)), center_y + int((center_y / 0.925)) ))
        time.sleep(0.5)
        y= center_y / i
        win32api.SetCursorPos((center_x + int((center_x / 7.182)), center_y + int(center_y / 0.77)))
        time.sleep(0.5)

        win32api.SetCursorPos((center_x + int((center_x / 7.182)), center_y + int(center_y / 0.66)))
        time.sleep(0.5)
        y = (num - 3 * i)/3
        win32api.SetCursorPos((center_x + int((center_x / 7.182)), center_y + int(center_y / 0.57)))
        time.sleep(0.5)
        y= num - 4 * i
        win32api.SetCursorPos((center_x + int((center_x / 7.182)), center_y + int(y * 4)))
        time.sleep(0.5)
        y = num - 5 * i
        win32api.SetCursorPos((center_x + int((center_x / 7.182)), center_y + int((center_y / y))))

def setBeizhuNew(param):
    '''2024-03-30最新'''

    #简字描述,数字标记
    simplecheck = param.get('simplecheck')
    numcheck = param.get('numcheck')
    list = param.get('list')
    if list is None or len(list)<=0:
        return

    # 读取配置文件
    configFile = {}
    configfileaddr = pathlib.Path(__file__).parent.parent.parent.resolve().as_posix() + '/' + Gv.configfileaddr
    try:
        with open(configfileaddr, 'r') as f:
            configFile = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")
    if configFile is None or len(configFile)<=0:
        return
    bz_list = configFile.get(Gv.BZ)
    bz_one_list = configFile.get(Gv.BZONE)
    interval = configFile.get(Gv.INTERVAL)
    #速度
    speed = configFile.get(Gv.BZSPEED)
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄窗口置顶
        win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                              win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)
        # 通过句柄将窗口放到最前
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
        win32gui.SetForegroundWindow(hwnd)
        in_wait_time = interval_wait_time[speed]
        wait_time = between_wait_time[speed]
        bd_num_wait_time = num_wait_time[speed]
        num_interval = num_interval_wait_time[speed]
        for item in list:
            code = item.get('code')
            text = item.get('text')
            num = item.get('num')
            #设置备注
            setRemarks(bz_list,code,text,simplecheck,speed)
            if numcheck:
                #标记数字
                time.sleep(wait_time)
                setMarkNum(num,bz_one_list,interval,bd_num_wait_time,num_interval)
            time.sleep(in_wait_time)
def setMarkNum(num,bz_one_list,interval,bd_num_wait_time,num_interval):
    '''标记数字'''
    if int(num)>9:
        num = '9'
    for i, xystr in enumerate(bz_one_list):
        x, y = xystr.split(',')
        if i == 2:
            y = int(y) + ((int(num) - 1) * int(interval))
        win32api.SetCursorPos((int(x), int(y)))
        if i == 0:
            pyautogui.rightClick()
            time.sleep(bd_num_wait_time)
        else:
            pyautogui.click()
        time.sleep(num_interval)
def setRemarks(bz_list,code,text,simplecheck,speed):
    # 将字符串转换为虚拟键码列表
    pressdownCode(code)
    pressdown(win32con.VK_RETURN)
    time.sleep(0.1)
    pressdown(win32con.VK_INSERT)
    pressdownCtrlOr('I')
    time.sleep(bz_wait_time[speed])
    pyperclip.copy(text)
    pressdownCtrlOr('A')
    pressdown(win32con.VK_DELETE)
    # 获取标准输出句柄
    # 发送消息
    time.sleep(0.1)
    pressdownCtrlOr('V')
    for i,xystr in enumerate(bz_list):
        if not simplecheck and i == 0:
            #当简字描述没勾选，跳过一回合
            continue
        x, y = xystr.split(',')
        win32api.SetCursorPos((int(x), int(y)))
        time.sleep(0.1)
        pyautogui.click()
        if i == 0:
            pressdownCtrlOr('A')
            time.sleep(0.1)
            pressdownCtrlOr('V')
            time.sleep(0.1)

def setBeizhu(code,text,xoff,yoff,y2off,check,num,checkBox_numbz):
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄窗口置顶
        win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)
        # 通过句柄将窗口放到最前
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
        win32gui.SetForegroundWindow(hwnd)
        # 要发送的字符串
        setBeiZhuByCode(code,text,hwnd,xoff,yoff,y2off,check)
        if checkBox_numbz:
            #截图
            monitor_rect = win32gui.GetWindowRect(hwnd)
            jietu(monitor_rect,num)

def jietu(monitor_rect,numStr):
    if numStr is None:
        return
    num = int(numStr)
    if num>9:
        num = 9
    # 计算副屏中央位置的坐标
    time.sleep(0.2)
    center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2 // 4
    center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2 // 4
    win32api.SetCursorPos((center_x, center_y))
    pyautogui.rightClick()
    time.sleep(1)
    left = 2160
    width = 1920
    height = 1080
    location = {'top': 250, 'left': 277, 'width': 52, 'height': 13}
    # save_image(left,width,height)
    # location = bdyApi.main(Gv.BJGP)
    print(location)
    if location is None:
        return
    leftoff = location['left'] + location['width']
    topoff= location['top']
    heightoff = location['height'] // 2
    pyautogui.moveTo(left + leftoff, topoff + heightoff)
    time.sleep(0.5)
    #save_image(left,width,height)
    # location2 = bdyApi.main(Gv.BJGPEnum.value_by_another_value(num))
    # if location2 is None:
    #     return
    # leftoff2 = int(((location2['left']-location2['width']) - leftoff))

    topoff2 = (num - 1) * 35
    pyautogui.moveRel(300, topoff2)
    time.sleep(0.5)
    pyautogui.click()

def save_image(left,width,height):
    sct = mss.mss()
    img = sct.grab({'top': 0, 'left': left, 'width': width, 'height': height})  # 截图
    img = cv2.cvtColor(numpy.array(img), cv2.COLOR_BGR2GRAY)  # 转换色值
    img = cv2.cvtColor(numpy.array(img), cv2.COLOR_GRAY2BGRA)  # 转换色值
    jsonfileaddr = pathlib.Path(__file__).parent.parent.parent.resolve().as_posix() + '/' + Gv.pngfileaddr
    cv2.imwrite(jsonfileaddr, img)

def movedate(days:None,day:None):
    if days is None or days == 0 or day is None:
        return
    nowdate = datetime.now().strftime('%Y-%m-%d')
    # if day == nowdate:
    #     return
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    x,y = pyautogui.position()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        print(window)
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄窗口置顶
        win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                              win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER | win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)
        # 通过句柄将窗口放到最前
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
        win32gui.SetForegroundWindow(hwnd)
        # 要发送的字符串
        monitor_rect = win32gui.GetWindowRect(hwnd)
        center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2 + (
                    monitor_rect[2] - monitor_rect[0]) // 3 - (monitor_rect[2] - monitor_rect[0]) // 3 // 3 // 3 // 5
        center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2 // 3
        time.sleep(0.3)
        win32api.SetCursorPos((center_x, center_y))
        pyautogui.click()
        time.sleep(0.1)
        for i in range(days):
            pressdown(win32con.VK_LEFT)
        win32api.SetCursorPos((x, y))

def bz_Record(bzList:None,text,type):
    '''备注录制'''
    pyautogui.FAILSAFE = False
    thsName = '同花顺('
    # 获取所有窗口句柄
    windows = pyautogui.getAllTitles()
    # 遍历所有窗口，查找特定窗口的选中状态
    for window in windows:
        # 判断窗口标题是否匹配特定字符串
        if thsName not in window:
            continue
        # 通过窗口标题获取句柄
        hwnd = win32gui.FindWindow(None, window)
        # 通过句柄将窗口放到最前
        if win32gui.IsIconic(hwnd):
            win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
        win32gui.SetForegroundWindow(hwnd)

        pressdownCode('000001')
        pressdown(win32con.VK_RETURN)
        time.sleep(0.1)
        if type is None:
            continue
        if type<=1:
            pressdownCtrlOr('I')
            time.sleep(2)
            if type == 0:
                pyperclip.copy(text)
                pressdownCtrlOr('A')
                pressdown(win32con.VK_DELETE)
                time.sleep(0.1)
                pressdownCtrlOr('V')
                for xystr in bzList:
                    x,y = xystr.split(',')
                    win32api.SetCursorPos((int(x), int(y)))
                    time.sleep(1)
                    pyautogui.click()
                    pressdownCtrlOr('A')
                    time.sleep(0.1)
                    pressdownCtrlOr('V')
                    time.sleep(0.1)
        else:
            if bzList is None or len(bzList)<2:
                return
            for i,xystr in enumerate(bzList):
                if i>=2:
                    return
                x,y = xystr.split(',')
                win32api.SetCursorPos((int(x), int(y)))
                if i==0:
                    pyautogui.rightClick()
                    time.sleep(1)
                else:
                    pyautogui.click()
                time.sleep(0.1)



def jietutest(monitor_rect,numStr):
    if numStr is None:
        return
    num = int(numStr)
    if num>9:
        num = 9
    # 计算副屏中央位置的坐标
    time.sleep(0.2)
    center_x = monitor_rect[0] + (monitor_rect[2] - monitor_rect[0]) // 2 // 4
    center_y = monitor_rect[1] + (monitor_rect[3] - monitor_rect[1]) // 2 // 4
    print(monitor_rect)
    win32api.SetCursorPos((2364, 128))
    return
    pyautogui.rightClick()
    time.sleep(1)
    left = 0
    width = 1920
    height = 1080
    location = {'top': 250, 'left': 277, 'width': 52, 'height': 13}
    # save_image(left,width,height)
    # location = bdyApi.main(Gv.BJGP)
    print(location)
    if location is None:
        return
    leftoff = location['left'] + location['width']
    topoff= location['top']
    heightoff = location['height'] // 2
    #370
    pyautogui.moveTo(2481 , 263)
    time.sleep(0.5)
    pyautogui.click()
    #save_image(left,width,height)
    # location2 = bdyApi.main(Gv.BJGPEnum.value_by_another_value(num))
    # if location2 is None:
    #     return
    # leftoff2 = int(((location2['left']-location2['width']) - leftoff))

    topoff2 = (num  - 1) * 22.625
    print(263 + topoff2)
    pyautogui.moveTo(2676 , 263 + topoff2)
    time.sleep(0.5)
    #pyautogui.click()

if __name__ == '__main__':
    movedate(2,'2024-10-28')











